package com.cz.nongyetongv5.application;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Vibrator;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.SDKInitializer;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.bean.VersionBean;
import com.cz.nongyetongv5.dialog.ShaUtils;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.EmojiUtil;
import com.ronri.ams.bean.loginbean;
import com.ronri.ams.bean.sample_info;
import com.ronri.ams.bean.systemConfig;
import com.ronri.common.DensityUtil;
import com.ronri.common.FileManager;
import com.ronri.mapapi.location.service.LocationService;
import com.zhy.autolayout.utils.ScreenUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.loader.opendroid.app.DroidApplication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

public class InitApplication extends DroidApplication {
    /**
     * 当前版本
     */
    private VersionBean version;

    /**
     * 服务器版本
     */
    private VersionBean maxVersion;

    /**
     * Emoji表情的工具类
     */
    private EmojiUtil emojiUtil = null;

    /**
     * 受检单位经纬度
     * 拍照用
     */
    public static Double photolat;
    public static Double photolng;
    public static String organization;

//    public static String newUrl = "http://192.168.0.78:8080/api/";
//    public static String markUrl = "http://192.168.0.78:8081/mark/api/";
//    public static final String BASE_URL_ENT_PIC = "http://192.168.0.78:8066/";

    //    public static String newUrl = "http://58.216.138.250:8082/assist/api/";
    //    public static String markUrl = "http://58.216.138.250:8089/mark/api/";
    //    public static final String BASE_URL_ENT_PIC = "http://58.216.138.250:8066/";

    public static String newUrl = "http://xgy.czfood360.cn:8010/api/";
    public static String markUrl = "http://mark.czfood360.cn:8022/api/";
    public static final String BASE_URL_ENT_PIC = "http://jg.czfood360.cn/";

    public boolean m_bKeyRight = true;
    //    BMapManager mBMapManager = null;

    private List<Activity> activities = new ArrayList<Activity>();

    public static Context sContext;

    final public static int Activity_RESULT_GET_PHOTO = 9000;

    private static InitApplication instance;

    private static Context mContext;

    private static String mVersionInfo = "";
    private static String mAbout = "";

    // 照片信息保存路径
    public static String PhotoSavePath = "";

    // 数据环境配置
    public static systemConfig SystemConfig = null;

    // 登录信息
    public static loginbean LoginInfo = null;

    // 定位服务
    public static LocationService locationService;

    public static int ScreenWidth = 0;
    public static int ScreenHeight = 0;

    // 服务
    public Vibrator mVibrator;

    // 样品编辑信息
    public static sample_info gSampleInfo = new sample_info();

    public VersionBean getVersion() {
        return version;
    }

    public void setVersion(VersionBean version) {
        this.version = version;
    }

    public VersionBean getMaxVersion() {
        return maxVersion;
    }

    public void setMaxVersion(VersionBean maxVersion) {
        this.maxVersion = maxVersion;
    }

    /**
     * 是否存在新版本
     *
     * @return
     */
    public boolean hasNewVersion() {

        if (getMaxVersion() == null) {

            return false;
        }

        if (CharsetUtil.isNotNull(getVersion().getVersion())
                && CharsetUtil.isNotNull(getMaxVersion().getVersion())) {

            if (getMaxVersion().getVersion().compareToIgnoreCase(
                    getVersion().getVersion()) > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 更新日志
     */
    public String getUpdateLog() {

        StringBuffer logBuf = new StringBuffer();

        if (getMaxVersion() != null && getMaxVersion().getLog().size() > 0) {

            for (int i = 0; i < getMaxVersion().getLog().size(); i++) {

                String log = getMaxVersion().getLog().get(i);

                logBuf.append((i + 1) + "." + log + "\n");

            }
        }

        return logBuf.toString();

    }

    /**
     * 保持单利的Emoji表情
     *
     * @return
     */
    public EmojiUtil getEmojiUtil() {

        if (emojiUtil == null) {
            emojiUtil = new EmojiUtil(this);
        }

        return emojiUtil;
    }

    public void setEmojiUtil(EmojiUtil emojiUtil) {
        this.emojiUtil = emojiUtil;
    }

    /**
     * 当应用创建的时候
     */
    @Override
    public void onCreate() {
        super.onCreate();
        sContext = getApplicationContext();

        // 初始化JPush
        JPushInterface.init(getApplicationContext());

        // 初始化emoji表情工具类
        getEmojiUtil();

        //        AutoLayoutConifg.getInstance().useDeviceSize().init(this);

        instance = this;
        mContext = getApplicationContext();

        /*** 初始化定位sdk，建议在Application中创建 ***/
        locationService = new LocationService(getApplicationContext());
        mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());

        // 获取当前设备的dpi
        DensityUtil.getScale(this);
        int[] screenSize = ScreenUtils.getScreenSize(InitApplication.getContext(), true);

        ScreenWidth = screenSize[0];
        ScreenHeight = screenSize[1];

        // 保存照片路径
        PhotoSavePath = Environment.getExternalStorageDirectory().toString() + getResources().getString(R.string.Photo_Result_Save_Path);

        // 获取配置信息
        SystemConfig = JSON.parseObject(FileManager.getFromAssets(getResources(), "AppConfig/RemoteDataBaseConfig.json"), systemConfig.class);

        mVersionInfo = FileManager.getFromAssets(getResources(), "AppConfig/AppVersion.txt").replace("\\n", "\n");
        mAbout = FileManager.getFromAssets(getResources(), "AppConfig/about.txt").replace("\\n", "\n");


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Long nonce = System.nanoTime();
                        Long timestamp = System.currentTimeMillis();
                        String signature = ShaUtils.shaEncrypt(nonce.toString() + timestamp.toString());
                        Request request = chain.request();
                        Request authorised = request.newBuilder()
                                .header("nonce", nonce.toString())
                                .header("timestamp", timestamp.toString())
                                .header("signature", signature)
                                .build();
                        return chain.proceed(authorised);
                    }
                })
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Log.v(TAG, "request:" + request.toString());
                        long t1 = System.nanoTime();
                        okhttp3.Response response = chain.proceed(chain.request());
                        long t2 = System.nanoTime();
                        Log.v(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                        okhttp3.MediaType mediaType = response.body().contentType();
                        String content = response.body().string();
                        Log.i(TAG, "response body:" + content);
                        return response.newBuilder()
                                .body(okhttp3.ResponseBody.create(mediaType, content))
                                .build();
                    }
                })
                .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                .readTimeout(60000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();
        OkHttpUtils.initClient(okHttpClient);

        //        initEngineManager(this);

        //        SDKInitializer.initialize(getApplicationContext());
    }


    //    public void initEngineManager(Context context) {
    //        if (mBMapManager == null) {
    //            mBMapManager = new BMapManager();
    //        }
    //
    //        if (!mBMapManager.init(new MyGeneralListener())) {
    //            Toast.makeText(InitApplication.getInstance().getApplicationContext(),
    //                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
    //        }
    //    }


    //    // 常用事件监听，用来处理通常的网络错误，授权验证错误等
    //    public static class MyGeneralListener implements MKGeneralListener {
    //
    //        @Override
    //        public void onGetNetworkState(int iError) {
    //            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
    //                Toast.makeText(InitApplication.getInstance().getApplicationContext(), "您的网络出错啦！",
    //                        Toast.LENGTH_LONG).show();
    //            }
    //            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
    //                Toast.makeText(InitApplication.getInstance().getApplicationContext(), "输入正确的检索条件！",
    //                        Toast.LENGTH_LONG).show();
    //            }
    //            // ...
    //        }
    //
    //        @Override
    //        public void onGetPermissionState(int iError) {
    //            //非零值表示key验证未通过
    //            if (iError != 0) {
    //                //授权Key错误：
    //                //                Toast.makeText(InitApplication.getInstance().getApplicationContext(),
    //                //                        "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常！error: "+iError, Toast.LENGTH_LONG).show();
    //                InitApplication.getInstance().m_bKeyRight = false;
    //            }
    //            else{
    //                InitApplication.getInstance().m_bKeyRight = true;
    //                //            	Toast.makeText(InitApplication.getInstance().getApplicationContext(),
    //                //                        "key认证成功", Toast.LENGTH_LONG).show();
    //            }
    //        }
    //    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        // 初始化JPush
        JPushInterface.stopPush(getApplicationContext());
    }

    public List<Activity> getActivities() {
        return activities;
    }

    public static Context getContext() {
        return mContext;
    }

    public static InitApplication getInstance() {
        // 因为我们程序运行后，Application是首先初始化的，如果在这里不用判断instance是否为空
        return instance;
    }

    public static String getAbout() {
        return mAbout;
    }

    /***
     * 获取版本修正信息
     * @param context
     * @return
     */
    public static String getVersionInfo(Context context) {
        return mVersionInfo;
    }

    /***
     * 版本名
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    /***
     * 版本号
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    /****
     * 获取App包信息
     * @param context
     * @return
     */
    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
